package org.shj.socket;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

	public static void start(){
		try{
			ServerSocket server = new ServerSocket(9999);
			
			while(true){
				Socket socket = server.accept();
				new Thread(new Runnable(){
					public void run(){
						try{
							/*BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
							String line = null;
							StringBuffer sb = new StringBuffer();
							while((line = br.readLine()) != null){
								sb.append(line);
							}
							
							System.out.println(sb.toString());*/
							InputStream inputStream = socket.getInputStream();
			                DataInputStream dataInputStream =new DataInputStream(inputStream);
			                byte b = dataInputStream.readByte();
			                int len = dataInputStream.readInt();
			                byte[] data =new byte[len];
			                dataInputStream.readFully(data);
			                String str =new String(data);
			                System.out.println("获取的数据类型为："+b);
			                System.out.println("获取的数据长度为："+len);
			                System.out.println("获取的数据内容为："+str);

							//返回给客户端
			                DataOutputStream dataOutputStream =new DataOutputStream(socket.getOutputStream());
			    			int type = 1;
			    			data = ("I received:" + str).getBytes();
			    			len = data.length;
			    			dataOutputStream.writeByte(type);
			    			dataOutputStream.writeInt(len);
			    			dataOutputStream.write(data);
			    			dataOutputStream.flush();
						}catch(Exception e){
							e.printStackTrace();
						}
					}
				}).start();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args){
		start();
	}
}
